//
// Created by Administrator on 2021/1/31 0031.
//

#include "JqhQueue.h"

JqhQueue::JqhQueue(JqhPlayStatus *playStatus) {
    this->playStatus = playStatus;
    pthread_cond_init(&condPacket, NULL);
    pthread_mutex_init(&mutexPacker, NULL);
}

JqhQueue::~JqhQueue() {
    clearAvpacket();
    pthread_cond_destroy(&condPacket);
    pthread_mutex_destroy(&mutexPacker);
}

int JqhQueue::putAVPacket(AVPacket *packet) {
    pthread_mutex_lock(&mutexPacker);

    queuePacket.push(packet);
//    if (LOG_DEBUG) {
//        LOGD("添加队列，当前个数为: %d", queuePacket.size());
//    }
    pthread_cond_signal(&condPacket);

    pthread_mutex_unlock(&mutexPacker);
    return 0;
}

int JqhQueue::getAVPacket(AVPacket *packet) {
    pthread_mutex_lock(&mutexPacker);

    if (queuePacket.size() > 0) {
        AVPacket *avPacket = queuePacket.front();
        if (av_packet_ref(packet, avPacket) == 0) {
            queuePacket.pop();
        }
//        av_packet_free(&avPacket);
//        av_free(avPacket);
//        avPacket = NULL;

//        if (LOG_DEBUG) {
//            LOGD("取出队列，当前个数为: %d", queuePacket.size());
//        }
    } else {
        pthread_cond_wait(&condPacket, &mutexPacker);
    }
    pthread_mutex_unlock(&mutexPacker);
    return 0;
}

int JqhQueue::getQueueSize() {
    int size = 0 ;
    pthread_mutex_lock(&mutexPacker);
    size = this->queuePacket.size();
    pthread_mutex_unlock(&mutexPacker);
    return size;
}

void JqhQueue::clearAvpacket() {
    pthread_cond_signal(&condPacket);
    pthread_mutex_lock(&mutexPacker);

    while (!queuePacket.empty()) {
        AVPacket *packet = queuePacket.front();
        queuePacket.pop();
        av_packet_free(&packet);
        av_free(packet);
        packet = NULL;
    }

    pthread_mutex_unlock(&mutexPacker);
}
